<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.moshiName"
        placeholder="模式名称"
        class="filter-item search-input"
        clearable
        @keyup.enter.native="handleFilter"
      />
       <el-input
        v-model="listQuery.mobile"
        placeholder="手机号"
        class="filter-item search-input"
        clearable
        @keyup.enter.native="handleFilter"
      />
       <el-date-picker v-model="listQuery.startTime" placeholder="创建时间（开始）" type="date" style="width : 150px;" class="search-input filter-item" />
      <el-date-picker v-model="listQuery.endTime" placeholder="创建时间（结束）" type="date" style="width : 150px" class="search-input filter-item" />
      <el-select
        v-model="listQuery.peer"
        placeholder="分公司"
        clearable
        style="width: 190px"
        class="filter-item search-input"
      >
        <el-option v-for="item in peerOptions" :key="item.peerId" :label="item.name" :value="item.peerId" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="handleExport">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <!--      <el-table-column label="线路ID" width="80px" align="center">-->
      <!--        <template slot-scope="{row}">-->
      <!--          <span>{{ row.ID }}</span>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="模式名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.moshiName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
       <el-table-column label="用户名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="金额" align="center">
        <template slot-scope="{row}">
          <span>{{ row.money }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nums }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status === '已下架' ? 'danger' : (row.status === '草稿' ? 'info' : 'success') ">
            {{ row.status === '草稿' ? '&nbsp;草&nbsp;&nbsp;稿&nbsp;' : row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="分公司ID" align="center">
        <template slot-scope="{row}">
          <span v-html="row.peerId" /> 
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <!--        <template slot-scope="{row,$index}">-->
        <template slot-scope="{row}">
          <el-button size="small" type="primary" icon="el-icon-edit" @click="handleUpdate(row)">编辑</el-button>

          <!--        <el-button size="small" type="danger" plain>删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="rigth" label-width="25%">
        <el-form-item label="模式名称" >
          <el-input v-model="temp.moshiName" class="window-inp" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="temp.mobile" class="window-inp" />
        </el-form-item>
         <el-form-item label="用户名">
          <el-input v-model="temp.userName" class="window-inp" />
        </el-form-item>
         <el-form-item label="金额">
          <el-input v-model="temp.money" class="window-inp" />
        </el-form-item>
         <el-form-item label="数量">
          <el-input v-model="temp.nums" class="window-inp" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="temp.status" placeholder="状态" class="window-inp" clearable>
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="分公司">
          <el-select v-model="temp.peer" placeholder="分公司" class="window-inp" clearable>
            <el-option v-for="item in peerOptions" :key="item.peerId" :label="item.name" :value="item.peerId" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('table.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('table.confirm') }}
        </el-button>
      </div>
    </el-dialog>

    

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { list, update, add } from '@/api/modeOrderManagement'
import { listSelection } from '@/api/selectOptions'
import Pagination from '@/components/Pagination'

export default {
  components: {
    Pagination
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        // page: 1,
        moshiName: undefined, // 模式名称
        mobile: undefined, // 手机号
        startTime: undefined, // 创建时间（开始）
        endtTime: undefined ,// 创建时间（结束）
        peerId : undefined //分公司id
        // csv: undefined // 为1时，导出
      },
      temp: {
        id: undefined,
        moshiName: undefined,
        mobile: undefined,
        userName: undefined,
        money: undefined,
        nums: undefined,
        status: undefined,
        peerId: undefined,
        
      },
      startCityOptions: undefined,
      peerOptions: undefined,
      statusOptions: [{ label: '草稿', value: '0' }, { label: '销售中', value: '1' }, { label: '已下架', value: '2' }],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
    }
  },
  created() {
    this.getPeerOptions()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      list(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      })
//       this.list = [{
//         "id":"2",
//         "moshiName":"测试",
//         "mobile":"15242693000",
//         "money":"18",
//         "peerId":"1",
//         "status":"1",
//         "userName":"测试",
//         "nums":"18",
//         "createTime":"2021‑07‑08 00:00:01"
//       },{
//         "id":"3",
//         "moshiName":"测2试",
//         "mobile":"15242693000",
//         "money":"188",
//         "peerId":"1",
//         "status":"1",
//         "userName":"测试2",
//         "nums":"187",
//         "createTime":"2021‑07‑18 00:00:01"
//       },{
//         "id":"4",
//         "moshiName":"测4试",
//         "mobile":"15242693000",
//         "money":"188",
//         "peerId":"1",
//         "status":"1",
//         "userName":"测试4",
//         "nums":"187",
//         "createTime":"2021‑07‑18 00:00:01"
//       },{
//         "id":"5",
//         "moshiName":"测5试",
//         "mobile":"15242693000",
//         "money":"188",
//         "peerId":"1",
//         "status":"1",
//         "userName":"测试5",
//         "nums":"187",
//         "createTime":"2021‑07‑18 00:00:01"
//       }]
      this.listLoading = false
    },
    getPeerOptions() {
      listSelection().then(response => {
        this.peerOptions = response.data
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleExport() {
      list(Object.assign(this.listQuery), 'arraybuffer').then(response => {
        const content = response
        // 组装a标签
        const elink = document.createElement('a')
        // 设置下载文件名
        elink.download = '附件.csv'
        elink.style.display = 'none'
        const blob = new Blob([content], { type: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel' })
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        document.body.removeChild(elink)
        this.listQuery.csv = 0
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      // console.log("row=========" , row)
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetTemp() {
      this.temp = {
        moshiName: '',
        mobile: '',
        userName: '',
        money: '',
        nums: 0,
        status: 0,
        peerId: undefined,

      }
    },
    updateData() {
      update(this.temp).then(response => {
        if (response.code === 200 || response.code === '200') {
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: '失败',
            message: '更新失败：' + response.msg,
            duration: 2000,
            type: 'error'
          })
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          add(this.temp).then(response => {
            if (response.code === 200 || response.code === '200') {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: '更新失败：' + response.msg,
                duration: 2000,
                type: 'error'
              })
            }
          })
        }
      })
    },

  }
}
</script>

<style>
.search-input {
  width: 150px;
  margin-right: 15px;
}

.window-inp {
  width: 50%;
  margin-left: 5%;
  float: left;
  margin: 0 1%;
}

.window-inp-s {
  width: 22%;
  margin: 0 1%;
}

.line-item {
  border: 1px solid #DCDFE6;
  border-radius: 5px;
  height: 200px;
  width: 85%;
  margin-left: 1%;
  overflow-x:auto;
}

.line-add {
  margin: 0 0 2% 1%;
  padding: 10px 6px;
}
.line-name{
  line-height: 25px;
  background: #9CD5B7;
  width: 99%;
  margin: 0.5% 0.5%;
  float: left;
  text-align: center;
}
</style>
